<?php
/**
 * Created by PhpStorm.
 * User: Sky
 * Date: 2017/7/27
 * Time: 上午11:30
 */

namespace app\librarys;

use app\models\Manager;
use app\models\Permission;
use app\models\SysExceptionLog;
use app\models\SysOperateLog;
use yii\web\Controller;

class BaseController extends Controller
{
    public $enableCsrfValidation = false;

    public function beforeAction($action)
    {
        if (!YII_DEBUG) {
            if (!\Yii::$app->session->has(Manager::SessionKey)) {
                $url = Tools::urlBase();
                $request_url = \Yii::$app->request->url;
                return $this->redirect("{$url}/site/login?request_url={$request_url}");
            }
        }
        try {
            $is_record_log = \Yii::$app->params['is_record_log'];
            if ($is_record_log == true) {
                // 记录请求日志
                $logId = SysOperateLog::add(
                    $action->controller->id,
                    $action->id,
                    $_GET,
                    $_POST,
                    Manager::getCurrentManager()['id'],
                    Manager::getCurrentManager()['name'],
                    $_SERVER['REMOTE_ADDR'],
                    $_SERVER['HTTP_USER_AGENT'],
                    $_SERVER['REQUEST_TIME']
                );
                \Yii::$app->session->set('request_manager_operate_log_id', $logId);
                \Yii::$app->session->set('request_manager_timestamp', Tools::getMillisecond());
            }
        } catch (\Exception $ex) {
        }
        // TODO log
//        if (YII_DEBUG) {
//            $currentManager = Manager::getCurrentManager();
//            if ($currentManager == null) {
//                return $this->redirect(['site/login', 'return_url' => \Yii::$app->request->url])->send();
//            }
//        }
        if (!YII_DEBUG) {
            $currentManager = Manager::getCurrentManager();
            if ($currentManager == null) {
                return $this->redirect(['site/login', 'return_url' => \Yii::$app->request->url])->send();
            }
            $hasPermission = Permission::hasPermission($action->controller->id, $action->id);
            if ($hasPermission) {
                return parent::beforeAction($action); // TODO: Change the autogenerated stub
            } else {
                throw new \Exception('无此权限,请重新登录!');
            }
        }
        return parent::beforeAction($action);
    }

    function runAction($id, $params = [])
    {
        try {
            return parent::runAction($id, $params);
        } catch (\Exception $ex) {
            $is_record_log = \Yii::$app->params['is_record_log'];
            if ($is_record_log == true) {
                // 记录异常日志
                $logId = \Yii::$app->session->get('request_manager_operate_log_id');
                if ($logId != null) {
                    SysOperateLog::setException($logId, $ex);

                    $operateLog = SysOperateLog::getById($logId);
                    if ($operateLog != null) {
                        SysExceptionLog::add(
                            $operateLog->controllerId,
                            $operateLog->actionId,
                            $operateLog->getParams,
                            $operateLog->postParams,
                            $operateLog->managerId,
                            $operateLog->managerName,
                            $operateLog->remoteAddr,
                            $operateLog->httpUserAgent,
                            $operateLog->createDatetime,
                            $ex
                        );
                    }
                }
            }
            throw $ex;
        }
    }

    public function afterAction($action, $result)
    {
        try {
            $is_record_log = \Yii::$app->params['is_record_log'];
            if ($is_record_log == true) {
                // 记录请求总共耗时(毫秒)
                $logId = \Yii::$app->session->get('request_manager_operate_log_id');
                if ($logId != null) {
                    $time = Tools::getMillisecond();
                    $time = $time - \Yii::$app->session->get('request_manager_timestamp');
                    SysOperateLog::setDurationTime($logId, $time);
                }
            }
        } catch (\Exception $ex) {
        }
        return parent::afterAction($action, $result);
    }

    /**
     * @param null|array|mixed $data
     * @param int $status 0:success
     * @param string $message
     * @return string   json result
     */
    public function renderJson($data = null, $status = 0, $message = 'success')
    {
        $result = [
            'status' => $status,
            'message' => $message,
            'data' => $data
        ];


        return json_encode($result, true);
    }
}